package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.ShopBean;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("login")
    @ResponseBody
    public String login(String userName, String psw, HttpServletRequest request) throws Exception {
        UserBean user = service.login(userName,psw);
        if(user == null){
            return "no";
        }
        request.getSession().setAttribute("loginUser",user);

        if("顾客".equals(user.getGrade())){
            request.getSession().setAttribute("shopMap",new HashMap<Integer, ShopBean>());
        }
        //用户信息转化为json字符串
        String userStr = new ObjectMapper().writeValueAsString(user);
        return userStr;
    }

    @RequestMapping("getUser")
    @ResponseBody
    public String getUser(HttpServletRequest request) throws Exception {
        UserBean user = (UserBean)request.getSession().getAttribute("loginUser");
        String userStr = new ObjectMapper().writeValueAsString(user);
        return userStr;
    }
}
